<template>
  <div class="page-header-index-wide">
    <!-- 活动类销售额 -->
    <a-row :gutter="24">
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="今日销售额(活动类)" v-bind:total="'￥'+todayActivityMoney |NumberFormat">
          <a-tooltip title="指标说明" slot="action">
            <!-- <a-icon type="info-circle-o" /> -->
          </a-tooltip>   
          
        </chart-card>
      </a-col>
    <!-- 活动类订单笔数 -->
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card  :loading="loading" title="今日订单笔数(活动类)" :total="todayActivityNumber | NumberFormat">
          <a-tooltip title="指标说明" slot="action">
            <!-- <a-icon type="info-circle-o" /> -->
          </a-tooltip>
          
          <!-- <template slot="footer">转化率 <span>60%</span></template> -->
        </chart-card>
      </a-col>
      <!-- 捐赠类销售额 -->
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="今日销售额(捐赠类)" :total="'￥'+todayDonationMoney  | NumberFormat">
          <a-tooltip title="指标说明" slot="action">
            <!-- <a-icon type="info-circle-o" /> -->
          </a-tooltip>
          
          <!-- <template slot="footer">日订单量<span> {{ '1234' | NumberFormat }}</span></template> -->
        </chart-card>
      </a-col>
      <!-- 捐赠类订单笔数 -->
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card  :loading="loading" title="今日订单笔数(捐赠类)" :total="todayDonationNumber |NumberFormat">
          <a-tooltip title="指标说明" slot="action">
            <!-- <a-icon type="info-circle-o" /> -->
          </a-tooltip>
          
          <!-- <div>
            <mini-progress color="rgb(19, 194, 194)" :target="80" :percentage="78" :height="8" />
          </div> -->
          <!-- <template slot="footer">
            <trend flag="down" style="margin-right: 16px;">
              <span slot="term">同周比</span>
              12%
            </trend>
            <trend flag="up">
              <span slot="term">日环比</span>
              80%
            </trend>
          </template> -->
        </chart-card>
      </a-col>
    </a-row>

    <!-- 饼图 -->
    <div class="" style="display:flex">
    <div style="width:50%;background-color: white; height: 300px; ">
    <div style="width:30%; margin-top: 20px;">
      <span style="padding:20px;font-size: 14px; ">累计活动金额</span><br>
    <span style="padding:30px;font-size: 28px;color: black;">￥{{activityPie.total | NumberFormat}}</span>
    </div>
    <div style="width:70%; margin-left: 80px;"><pie  :dataSource="activityPie.pieParam"></pie></div>
    </div>

    <div style="width:50%;background-color: white; height: 300px; margin-left: 20px;">
    <div style="width:30%; margin-top: 20px;">
      <span style="padding:20px;font-size: 14px; ">累计捐赠金额</span><br>
    <span style="padding:30px;font-size: 28px;color: black;">￥{{donationPie.total | NumberFormat}}</span>
    </div>
    <div style="width:70%; margin-left: 80px;"><pie  :dataSource="donationPie.pieParam"></pie></div>
    </div>
    </div>

  <!-- 折线图1 -->
  <div style="margin-top:20px">
    <a-col style="width:100%">
    <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard" style="width:100%">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item">
              <span style="padding-right:10px;"><a @click="this.get7DaysFoldData">近一周</a> 
               <a @click="this.get30DaysFoldData">近一月</a>
              <a @click="this.getThreeMonthsFoldData">近三月</a>
              <a @click="this.getHalfYearFoldData">近半年</a>
              <a @click="this.getOneYearFoldData">近一年</a>
              </span>
                
              <label for="rangePicker" >查询时间： </label>
              <!-- <a-range-picker  id="rangePicker" style="width: 256px;" /> -->
              <span>
            <j-date placeholder="起始时间" v-model="queryParam.begin" :showTime="true" dateFormat="YYYY-MM-DD" /></span>
            至
            <span><j-date placeholder="结束时间" v-model="queryParam.end" :showTime="true" dateFormat="YYYY-MM-DD" />
            
              <a-button style="margin-left:16px; " type="primary" @click="getMyFoldData" icon="search">查询</a-button>
            </span>
            </div>
            <!-- <a-range-picker :style="{width: '256px',}" /> -->
          </div>
          <a-tab-pane loading="true" tab="订单笔数" key="1">
            <a-row>
              <!-- <a-col :xl="24" :lg="12" :md="12" :sm="24" :xs="24"> -->
                <a-col style="width:100%">
                <!-- <bar title="订单笔数" :dataSource="barData"/> -->
                <line-chart-multid :fields="visitFields" :dataSource="orderCounts" :aliases="testAliases"></line-chart-multid>
              </a-col>
              <!-- <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24"> -->
                <!-- <rank-list title="门店销售排行榜" :list="rankList"/> -->
              <!-- </a-col> -->
            </a-row>
          </a-tab-pane>

          

        </a-tabs>
      </div>
    </a-card>
    </a-col>
  </div>

    <!-- 折线图2 -->
    <div style="margin-top:20px">
    <a-col style="width:100%">
    <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard" style="width:100%">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item">
              <span style="padding-right:10px;">
              <a @click="this.get7DaysFoldData">近一周</a> 
               <a @click="this.get30DaysFoldData">近一月</a>
              <a @click="this.getThreeMonthsFoldData">近三月</a>
              <a @click="this.getHalfYearFoldData">近半年</a>
              <a @click="this.getOneYearFoldData">近一年</a>
              </span>
                
              <label for="rangePicker" >查询时间： </label>
              <!-- <a-range-picker id="rangePicker" style="width: 256px;" /> -->
              <span>
            <j-date placeholder="起始时间" v-model="queryParam.begin" :showTime="true" dateFormat="YYYY-MM-DD" /></span>
            至
            <span><j-date placeholder="结束时间" v-model="queryParam.end" :showTime="true" dateFormat="YYYY-MM-DD" />
            
              <a-button style="margin-left:16px; " type="primary" @click="getMyFoldData" icon="search">查询</a-button>
            </span>

            </div>
            <!-- <a-range-picker :style="{width: '256px',}" /> -->
          </div>
          

          <a-tab-pane loading="true" tab="订单金额" key="1">
            <a-row>
              <!-- <a-col :xl="24" :lg="12" :md="12" :sm="24" :xs="24"> -->
                <a-col style="width:100%">
                <!-- <bar title="订单笔数" :dataSource="barData"/> -->
                <line-chart-multid :fields="visitFields1" :dataSource="orderMoney" :aliases="testAliases1"></line-chart-multid>
              </a-col>
              <!-- <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24"> -->
                <!-- <rank-list title="门店销售排行榜" :list="rankList"/> -->
              <!-- </a-col> -->
            </a-row>
          </a-tab-pane>
          
        </a-tabs>
      </div>
    </a-card>
    </a-col>
  </div>

  </div>
</template>

<script>
  import ChartCard from '@/components/ChartCard'
  import ACol from "ant-design-vue/es/grid/Col"
  import ATooltip from "ant-design-vue/es/tooltip/Tooltip"
  import MiniArea from '@/components/chart/MiniArea'
  import MiniBar from '@/components/chart/MiniBar'
  import MiniProgress from '@/components/chart/MiniProgress'
  import RankList from '@/components/chart/RankList'
  import Bar from '@/components/chart/Bar'
  import LineChartMultid from '@/components/chart/LineChartMultid'
  import HeadInfo from '@/components/tools/HeadInfo.vue'
  import Pie from '@/components/chart/Pie.vue'

  import Trend from '@/components/Trend'
  import { getLoginfo,getVisitInfo } from '@/api/api'
  import { getAction } from '../../api/manage'

  const rankList = []
  // for (let i = 0; i < 7; i++) {
  //   rankList.push({
  //     name: '白鹭岛 ' + (i+1) + ' 号店',
  //     total: 1234.56 - i * 100
  //   })
  // }
  const barData = []
  for (let i = 0; i < 12; i += 1) {
    barData.push({
      x: `${i + 1}月`,
      y: Math.floor(Math.random() * 1000) + 200
    })
  }
  export default {
    name: "IndexChart",
    components: {
      ATooltip,
      ACol,
      ChartCard,
      MiniArea,
      MiniBar,
      MiniProgress,
      RankList,
      Bar,
      Trend,
      LineChartMultid,
      HeadInfo,
      Pie
    },
    data() {
      return {
        // 饼状图数据
        activityPie:{
          total:"",
          pieParam:[
                    ],
        },
        donationPie:{
          total:"",
          pieParam:[],
        },
        totalDonationMoney:"",
        todayActivityMoney:"",
        todayDonationMoney:"",
        todayActivityNumber:"",
        todayDonationNumber:"",
        loading: true,
        center: null,
        rankList,
        barData,
        loginfo:{},

        //折线图数据
        //订单笔数
        orderCounts:[],
        //别名
        visitFields:['activityOrderCounts', 'donationOrderCounts'],
        testAliases:[{field:'activityOrderCounts',alias:'活动类'},{field:'donationOrderCounts',alias:'捐赠类'}],
        //订单金额
        orderMoney:[],
        visitFields1:['activityOrderMoney', 'donationOrderMoney'],
        testAliases1:[{field:'activityOrderMoney',alias:'活动类'},{field:'donationOrderMoney',alias:'捐赠类'}],

        queryParam:{
          begin:"",
          end:"",
        },

        indicator: <a-icon type="loading" style="font-size: 24px" spin />
      }
    },
    created() {
      setTimeout(() => {
        this.loading = !this.loading
      }, 1000)
      this.initLogInfo();
      this.sendRequest();
      const a = this.format();
    
    },
    methods: {
      test(){
        getAction('/templeDashboard/dashBoardDateQuery',{begin:'2022-06-01 00:00:00',end:'2022-06-31 00:00:00'}).then(res=>{if(res.success){
          var resdata = this.get7DaysFoldParam(res.result.activity7DayData,res.result.donation7DayData,7);
          console.log(resdata)
           this.orderCounts  =resdata[0];
           this.orderMoney = resdata[1];
           
          }
          else{
            alert('请求折线图数据失败')
          }})
      },

      //获取前num月月份
      getBeforeMonth(num,time){
        let n = num;
            let d = '';
            if(time) {
                d = new Date(time);
            } else {
                d = new Date();
            }
            let year = d.getFullYear();
            let mon = d.getMonth() + 2;
            // console.log(mon)
            var s = new Array();
            for(let a =0;a<num;a++)
            {
              mon--;
              if(mon==0){
                year=year-1;
                mon=12;
              }
              let ym =year +"-" + "0"+mon;
              s.push(ym);
            }
            console.log(s)
            return s;
      },
      
      //获取前num天日期
      getAgoDate(num){
            var arr = [];
            for(let a =0;a<num;a++){
             var s =  this.getBeforeDate(a);
              arr.push(s);
            }
            return arr
      },
      getBeforeDate(num, time) {
            let n = num;
            let d = '';
            if(time) {
                d = new Date(time);
            } else {
                d = new Date();
            }
            let year = d.getFullYear();
            let mon = d.getMonth() + 1;
            let day = d.getDate();
            if(day <= n) {
                if(mon > 1) {
                    mon = mon - 1;
                } else {
                    year = year - 1;
                    mon = 12;
                }
            }
            d.setDate(d.getDate() - n);
            year = d.getFullYear();
            mon = d.getMonth() + 1;
            day = d.getDate();
            let s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
            return s;
        },

      //获取当前日期
      format () {
        var date = new Date()
        var month = date.getMonth() + 1
        var strDate = date.getDate()
        if (month >= 1 && month <= 9) {
          month = '0' + month
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = '0' + strDate
        }
        var currentDate = date.getFullYear() + '-' + month + '-' + strDate 
        return currentDate
      },
      sendRequest(){
        //获取饼图数据
        getAction('/templeDashboard/dataStatistical',"").then(res=>{if(res.success){
          this.todayActivityMoney = res.result.todayActivityData.now_Activity_amount
          this.todayDonationMoney = res.result.todayDonationData.today_donation_amount
          this.todayActivityNumber = res.result.todayActivityData.now_Activity_nums
          this.todayDonationNumber = res.result.todayDonationData.today_donation_nums
          this.activityPie.total = res.result.todayActivityData.total_Activity_amount
          this.donationPie.total = res.result.todayDonationData.total_donation_amount
          this.getActivityPieParam(this.activityPie.pieParam,res.result.classifyActivityData);
          this.getDonationPieParam(this.donationPie.pieParam,res.result.classifyDonationData);
          }
          //获取折线图默认（近一周）数据
           this.get7DaysFoldData();
           
        });
      },
      //获取筛选框时间订单折线图数据
      getMyFoldData(){
        getAction('/templeDashboard/dashBoardDateQuery',this.queryParam).then(res=>{if(res.success){
          var resdata = this.get7DaysFoldParam(res.result.activityDateQuery,res.result.donationDateQuery,this.getDateDiff(this.queryParam.begin,this.queryParam.end));
          console.log(resdata)
           this.orderCounts  =resdata[0];
           this.orderMoney = resdata[1];
           
          }
          else{
            alert('请求折线图数据失败')
          }})
      },
      //统计天数
      getDateDiff(startDate, endDate){
          let startTime = new Date(Date.parse(startDate.replace(/-/g, "/"))).getTime();
          let endTime = new Date(Date.parse(endDate.replace(/-/g, "/"))).getTime();
          let dates = Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24);
          console.log(dates);
          if(dates>366){
            alert('选择的日期不能大于一年');
          }
          else{
            return dates;
          }
          
      },
      
      //获取七天订单折线图数据
      get7DaysFoldData(){
        getAction('/templeDashboard/query7DayData',"").then(res=>{if(res.success){
          var resdata = this.get7DaysFoldParam(res.result.activity7DayData,res.result.donation7DayData,7);
          console.log(resdata)
           this.orderCounts  =resdata[0];
           this.orderMoney = resdata[1];
           
          }
          else{
            alert('请求折线图数据失败')
          }})
      },
      

      //获取近一月订单折线图数据
      get30DaysFoldData(){
        getAction('/templeDashboard/queryOneMonthData',"").then(res=>{if(res.success){
          var resdata = this.get7DaysFoldParam(res.result.activityOneMonthData,res.result.donationOneMonthData,30);
          // console.log(resdata)
           this.orderCounts  =resdata[0];
           this.orderMoney = resdata[1];
           
          }
          else{
            alert('请求折线图数据失败')
          }})
      },
      //获取近三个月订单折线图数据
      getThreeMonthsFoldData(){
        getAction('/templeDashboard/queryThreeMonthData',"").then(res=>{
          if(res.success){
            var resdata = this.getMonthsFoldParam(res.result.activityThreeMonthData,res.result.donationThreeMonthData,3)
            console.log('发送半年请求成功')
            this.orderCounts = resdata[0];
            this.orderMoney = resdata[1];
          }
        else
        {
          console.log("请求半年数据失败")
        }
        })
      },
      //获取近半年订单折线图数据
      getHalfYearFoldData(){
        getAction('/templeDashboard/queryHalfData',"").then(res=>{
          if(res.success){
            var resdata = this.getMonthsFoldParam(res.result.activityHalfData,res.result.donationHalfData,6)
            console.log('发送半年请求成功')
            this.orderCounts = resdata[0];
            this.orderMoney = resdata[1];
          }
        else
        {
          console.log("请求半年数据失败")
        }
        })
      },
      //获取近一年订单折线图数据
      getOneYearFoldData(){
        getAction('/templeDashboard/queryOneYearData',"").then(res=>{
          if(res.success){
            var resdata = this.getMonthsFoldParam(res.result.activityOneYearData,res.result.donationOneYearData,12)
            console.log('发送半年请求成功')
            this.orderCounts = resdata[0];
            this.orderMoney = resdata[1];
          }
        else
        {
          console.log("请求半年数据失败")
        }
        })
      },
      //获取折线图数据（精确到日）
      get7DaysFoldParam(value,value1,days){
        var that =value;
        var that1 = value1;
        var arrTotal = new Array();
        var arrCount = new Array();
        var arrMoney = new Array();
        var dateRange =  this.getAgoDate(days);
        // console.log(dateRange)
        for(var a = 0;a<dateRange.length;a++){
          var obj1 = new Object();
          var obj2 = new Object();
          obj1.type= dateRange[a];
          obj1.activityOrderCounts = 0;
          obj1.donationOrderCounts = 0;
          obj2.type= dateRange[a];
          obj2.activityOrderMoney = 0;
          obj2.donationOrderMoney = 0;
          for( var b1 = 0; b1<that.length;b1++)
        {
          if(dateRange[a] == that[b1].activity_Date){
            obj1.type = dateRange[a];
            obj1.activityOrderCounts = that[b1].activity_OrderQuantity;
            break
          }
        }
        for(let c= 0;c<that1.length;c++){
          if(dateRange[a] == that1[c].donation_Date){
            obj1.donationOrderCounts = that1[c].donation_OrderQuantity;
            break
          }
        }

        for( var b2 = 0; b2<that.length;b2++)
        {
          if(dateRange[a] == that[b2].activity_Date){  
            obj2.type = dateRange[a];
            obj2.activityOrderMoney = that[b2].activity_OrderAmounts;
            break
          }
        }
        for(let c1= 0;c1<that1.length;c1++){
          if(dateRange[a] == that1[c1].donation_Date){
            obj2.donationOrderMoney = that1[c1].donation_OrderAmounts;
            break
          }
        }

        arrCount.push(obj1);
        arrMoney.push(obj2);
        }


        
        // console.log(arrMoney);
        arrTotal.push(arrCount);
        arrTotal.push(arrMoney);
        return arrTotal;
      },

      //获取折线图数据（精确到月）
      getMonthsFoldParam(value,value1,months){
        var that =value;
        var that1 = value1;
        var arrTotal = new Array();
        var arrCount = new Array();
        var arrMoney = new Array();
        var dateRange =  this.getBeforeMonth(months);
        // console.log(dateRange)
        for(var a = 0;a<dateRange.length;a++){
          
          var obj1 = new Object();
          var obj2 = new Object();
          obj1.type= dateRange[a];
          obj1.activityOrderCounts = 0;
          obj1.donationOrderCounts = 0;
          obj2.type= dateRange[a];
          obj2.activityOrderMoney = 0;
          obj2.donationOrderMoney = 0;
          
          for( var b1 = 0; b1<that.length;b1++)
        {
          
          if(dateRange[a] == that[b1].activity_Date){
            obj1.type = dateRange[a];
            obj1.activityOrderCounts = that[b1].activity_OrderQuantity;
            break
          }
        }
        for(let c= 0;c<that1.length;c++){
          
          if(dateRange[a] == that1[c].donation_Date){
            obj1.donationOrderCounts = that1[c].donation_OrderQuantity;
            break
          }
        }

        for( var b2 = 0; b2<that.length;b2++)
        {
          
          if(dateRange[a] == that[b2].activity_Date){  
            obj2.type = dateRange[a];
            obj2.activityOrderMoney = that[b2].activity_OrderAmounts;
            break
          }
        }
        for(let c1= 0;c1<that1.length;c1++){
          
          if(dateRange[a] == that1[c1].donation_Date){
            obj2.donationOrderMoney = that1[c1].donation_OrderAmounts;
            break
          }
        }
        
        arrCount.push(obj1);
        
        arrMoney.push(obj2);
        
        }

        arrCount.reverse();
        arrMoney.reverse();
        // console.log(arrMoney);
        arrTotal.push(arrCount);
        arrTotal.push(arrMoney);
        return arrTotal;
      },

      //获取饼状图数据
      getActivityPieParam(value1,value){
         var temp = value;
          for(let a = 0;a<temp.length;a++)
          {
            var obj = new Object();
            obj.item = temp[a].activity_type_name;
            obj.count =temp[a].total_activity_amount;
            value1.push(obj);
          } 
        },
        getDonationPieParam(value1,value){
         var temp = value;
          for(let a = 0;a<temp.length;a++)
          {
            var obj = new Object();
            obj.item = temp[a].donation_type_name;
            obj.count =temp[a].total_donation_amount;
            value1.push(obj);
          } 
        },
      initLogInfo () {
        getLoginfo(null).then((res)=>{
          if(res.success){
            Object.keys(res.result).forEach(key=>{
              res.result[key] =res.result[key]+""
            })
            this.loginfo = res.result;
          }
        })
        getVisitInfo().then(res=>{
          if(res.success){
             this.visitInfo = res.result;
           }
         })
      },
    }
  }
</script>

<style lang="less" scoped>

  .circle-cust{
    position: relative;
    top: 28px;
    left: -100%;
  }
  .extra-wrapper {
    line-height: 55px;
    padding-right: 24px;

    .extra-item {
      display: inline-block;
      margin-right: 24px;

      a {
        margin-left: 24px;
      }
    }
  }

  /* 首页访问量统计 */
  .head-info {
    position: relative;
    text-align: left;
    padding: 0 32px 0 0;
    min-width: 125px;

    &.center {
      text-align: center;
      padding: 0 32px;
    }

    span {
      color: rgba(0, 0, 0, .45);
      display: inline-block;
      font-size: .95rem;
      line-height: 42px;
      margin-bottom: 4px;
    }
    p {
      line-height: 42px;
      margin: 0;
      a {
        font-weight: 600;
        font-size: 1rem;
      }
    }
  }
</style>